package com.wendy.advice;

import com.wendy.utils.Constants;
import com.wendy.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhuwending
 */
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

    /**
     * 没有权限的处理
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    @ResponseBody
    public Object authorityHandler(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = StringUtils.isNotEmpty(header) && "XMLHttpRequest".equalsIgnoreCase(header);
        if (isAjax) {
            return ResponseUtil.errorResponse("没有权限", Constants.DEFAULT_AUTHORITY_PAGE);
        }
        ModelAndView mav = new ModelAndView("/error/403");
        mav.addObject("uri", request.getRequestURI());
        return mav;
    }

    /**
     * 500错误的处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object errorHandler(HttpServletRequest request, Exception e) {
        if (StringUtils.isEmpty(e.getMessage())) {
            log.error("java.lang.NullPointerException: null", e);
        } else {
            log.error(e.getMessage(), e);
        }
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = StringUtils.isNotEmpty(header) && "XMLHttpRequest".equalsIgnoreCase(header);
        if (isAjax) {
            String msg;
            if (StringUtils.isEmpty(e.getMessage())) {
                msg = "必要参数不能为空";
            } else {
                msg = e.getMessage();
            }
            return ResponseUtil.errorResponse("error", e, msg);
        }
        ModelAndView mav = new ModelAndView("/error/500");
        mav.addObject("uri", request.getRequestURI());
        mav.addObject("error", e);
        return mav;
    }
}
